class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        ans, i = 0, 0
        counter = {}

        for j, v in enumerate(fruits):

            if v in counter:
                counter[v] += 1
            else:
                counter[v] = 1
            
            while len(counter) >= 3:
                counter[fruits[i]] -= 1
                if  counter[fruits[i]] == 0:
                    del counter[fruits[i]]
                i += 1

            ans = max(ans, j - i + 1)

        return ans

# 官方
class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        ans, i = 0, 0
        counter = collections.Counter()

        for j, v in enumerate(fruits):
            counter[v] += 1
            
            while len(counter) >= 3:
                counter[fruits[i]] -= 1
                if  counter[fruits[i]] == 0:
                    del counter[fruits[i]]
                i += 1

            ans = max(ans, j - i + 1)

        return ans